import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '@/types/server'
import * as authApi from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const refreshToken = ref<string | null>(null)
  const loading = ref<boolean>(false)
  
  // 计算属性：是否已登录
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  
  // 初始化认证状态
  async function initAuth() {
    // 从本地存储中获取token和用户信息
    const savedToken = localStorage.getItem('auth_token')
    const savedRefreshToken = localStorage.getItem('refresh_token')
    const savedUserInfo = localStorage.getItem('user_info')
    
    if (savedToken && savedUserInfo) {
      token.value = savedToken
      refreshToken.value = savedRefreshToken
      user.value = JSON.parse(savedUserInfo)
      return true
    }
    
    return false
  }
  
  // 登录
  async function login(credentials: { username: string; password: string; remember?: boolean }) {
    loading.value = true
    
    try {
      const response = await authApi.login({ 
        username: credentials.username, 
        password: credentials.password 
      })
      
      // 保存token和用户信息
      token.value = response.access
      refreshToken.value = response.refresh
      
      // 保存到本地存储
      localStorage.setItem('auth_token', response.access)
      if (response.refresh) {
        localStorage.setItem('refresh_token', response.refresh)
      }
      
      // 获取用户信息
      await fetchCurrentUser()
      
      return true
    } catch (error) {
      console.error('登录失败', error)
      return false
    } finally {
      loading.value = false
    }
  }
  
  // 注册
  async function register(username: string, email: string, password: string) {
    loading.value = true
    
    try {
      const response = await authApi.register({ username, email, password })
      
      // 保存token和用户信息
      token.value = response.token
      user.value = {
        id: response.user_id,
        username: response.username,
        email: response.email
      }
      
      // 保存到本地存储
      localStorage.setItem('auth_token', response.token)
      localStorage.setItem('user_info', JSON.stringify(user.value))
      
      return true
    } catch (error) {
      console.error('注册失败', error)
      return false
    } finally {
      loading.value = false
    }
  }
  
  // 刷新token
  async function refreshAccessToken() {
    if (!refreshToken.value) return false
    
    try {
      const response = await authApi.refreshToken(refreshToken.value)
      token.value = response.access
      localStorage.setItem('auth_token', response.access)
      return true
    } catch (error) {
      console.error('刷新token失败', error)
      logout()
      return false
    }
  }
  
  // 获取当前用户信息
  async function fetchCurrentUser() {
    if (!token.value) return false
    
    loading.value = true
    
    try {
      const currentUser = await authApi.getCurrentUser()
      user.value = currentUser
      localStorage.setItem('user_info', JSON.stringify(currentUser))
      return true
    } catch (error) {
      console.error('获取用户信息失败', error)
      return false
    } finally {
      loading.value = false
    }
  }
  
  // 登出
  function logout() {
    authApi.logout()
    token.value = null
    refreshToken.value = null
    user.value = null
  }
  
  return {
    user,
    token,
    refreshToken,
    loading,
    isAuthenticated,
    initAuth,
    login,
    register,
    refreshAccessToken,
    fetchCurrentUser,
    logout
  }
}) 